package com.mlming.springboot.service.impl;

import com.mlming.springboot.dao.UserMapper;
import com.mlming.springboot.enums.ResponseEnum;
import com.mlming.springboot.enums.RoleEnum;
import com.mlming.springboot.pojo.User;
import com.mlming.springboot.service.UserService;
import com.mlming.springboot.vo.ResponseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public ResponseVo<User> register(User user) {
        // 首先验证用户名是否存在:
        int count = userMapper.countByUsername(user.getUsername());
        if(count > 0) {
            return ResponseVo.error(ResponseEnum.USER_EXISTS);
        }
        // 验证邮箱是否已经存在:
        count = userMapper.countByEmail(user.getEmail());
        if(count > 0) {
            return ResponseVo.error(ResponseEnum.EMAIL_EXISTS);
        }
        // 设置用户的身份为Customer
        user.setRole(RoleEnum.CUSTOMER.getCode());
        // 对密码进行MD5加密
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes(StandardCharsets.UTF_8)));
        // 写入数据库
        int res = userMapper.insertSelective(user);
        // 读出数据
        if(res > 0) {
            user = userMapper.selectByUserName(user.getUsername());
            return ResponseVo.success(user);
        } else {
            return ResponseVo.error(ResponseEnum.ERROR);
        }
    }

    @Override
    public ResponseVo<User> login(String username, String password) {
        User user = userMapper.selectByUserName(username);
        // 验证用户是否存在
        if(user == null) {
            return ResponseVo.error(ResponseEnum.USERNAME_OR_PASSWORD_ERROR);
        }
        // 验证密码
        if(!user.getPassword().equals(DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8)))) {
            return ResponseVo.error(ResponseEnum.USERNAME_OR_PASSWORD_ERROR);
        }
        // 如果都无误,根据接口文档,返回用户信息
        // 注意: password要屏蔽掉
        user.setPassword("");
        return ResponseVo.success(user);
    }

    @Override
    public ResponseVo<User> getUser(Integer userId) {
        User user = userMapper.selectByPrimaryKey(userId);
        return ResponseVo.success(user);
    }

}
